<?php

declare(strict_types=1);

namespace App\Validator;

use App\Constants\CustomModuleData\CustomModuleDataStatusEnum;
use Exception;
use Hyperf\Di\Annotation\Inject;
use Hyperf\Validation\Contract\ValidatorFactoryInterface;
use Hyperf\Stringable\StrCache;

/**
 * 自定义模块数据-验证器
 */
class CustomModuleDataValidator
{
        #[Inject]
        protected ValidatorFactoryInterface $validationFactory;

        /**
         * 验证规则-必须
         */
        public const array RULES = [
                'customModuleDataIds' => 'present|required|array',
                'customModuleDataId' => 'present|required',
                'customModuleIds' => 'present|required|array',
                'customModuleId' => 'present|required',
                'status' => 'present|required|in:' . CustomModuleDataStatusEnum::DEFINITION_1->value . ',' .
                        CustomModuleDataStatusEnum::DEFINITION_2->value,
        ];

        /**
         * 验证规则-非必须
         */
        public const array RULES_NOT_MUST = [
                'customModuleDataIds' => 'filled|array',
                'customModuleDataId' => 'filled',
                'customModuleIds' => 'filled|array',
                'customModuleId' => 'filled',
        ];

        /**
         * 验证
         * @param array $data
         * @param array $field
         * @param array $fieldNotMust
         * @throws Exception
         */
        public function validate(array $data, array $field = [], array $fieldNotMust = []): void
        {
                $arrRules = array_merge(
                        array_intersect_key(self::RULES, array_flip($field)),
                        array_intersect_key(self::RULES_NOT_MUST, array_flip($fieldNotMust))
                );
                $validator = $this->validationFactory->make($data, $arrRules, trans('validator'));
                if ($validator->fails()) {
                        $strErrorMessage = $validator->errors()->all()[0];
                        foreach ($field as $v) {
                                $strErrorMessage = str_replace(
                                        str_replace('_', ' ', StrCache::snake($v)),
                                        trans('customModuleData.field.' . $v), $strErrorMessage
                                );
                        }
                        throw new Exception($strErrorMessage);
                }
        }
}